package util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
/**
 * Abstract class. Extended by server and client
 *
 */
public abstract class SSLClientServer {
	protected int port;
	protected String host;
	protected SSLContext ctx;
	protected PrintWriter out;
	protected BufferedReader socketInput;
	protected SSLSocket socket;

	public SSLClientServer(int port, String host) {
		this.port = port;
		this.host = host;
		
	}
	/**
	 * Configures the use of certificates. 
	 * @param keystore
	 * @param pass
	 */
	public void setUpKeyManager( String keystore, String pass){
		System.setProperty("javax.net.ssl.trustStore", keystore);
		try {
	
			/*
			 * Set up a key manager for client authentication if asked by the
			 * server. Use the implementation's default TrustStore and
			 * secureRandom routines.
			 */
			try {
				KeyManagerFactory kmf;
				KeyStore ks;
				char[] passphrase = pass.toCharArray();

				ctx = SSLContext.getInstance("TLS");
				kmf = KeyManagerFactory.getInstance("SunX509");
				ks = KeyStore.getInstance("JKS");

				ks.load(new FileInputStream(keystore), passphrase);

				kmf.init(ks, passphrase);
				ctx.init(kmf.getKeyManagers(), null, null);

			} catch (Exception e) {
				throw new IOException(e.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void cleanUp() {
		try {
			socketInput.close();
			out.close();
			if(socket != null){
				socket.close();
			}			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
